package com.serverapk.ad;

import java.lang.reflect.Method;

import com.serverapk.BaseApplication;
import com.serverapk.PostNex;
import com.serverapk.R;
import com.serverapk.para.Common;
import com.serverapk.util.Util;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TopView extends LinearLayout {
    private String TAG = "TopView";
    private static Context context;
    private View view;
    private TextView version_name, bar_imei;
    private static TextView gprs_signal;
    private static ImageView signal_type_image;
    private String versioName = "";
    private TelephonyManager telephonyManager;
    private static int strength;
    public static boolean networkFlag = false;
    public static long signal;

    public TopView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initView();
        initVersion();
        initImei();
        initNetwork();
    }

    public void initView() {
        telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        // 加载布局
        view = LayoutInflater.from(context).inflate(R.layout.activity_topview, this);
        version_name = (TextView) view.findViewById(R.id.version_name);
        bar_imei = (TextView) view.findViewById(R.id.bar_imei);
        gprs_signal = (TextView) view.findViewById(R.id.gprs_signal);
        signal_type_image = (ImageView) view.findViewById(R.id.signal_type_image);
    }

    public void initVersion() {
        versioName = Util.getVersionName(context);
        version_name.setText(versioName);
    }

    @SuppressLint("NewApi")
    public void initImei() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                while (true) {

                    String imei;
                        if (Build.VERSION.SDK_INT >= 21) {
                            if (Build.VERSION.SDK_INT < 29)
                                imei = telephonyManager.getImei();
                            else
                                imei = Build.getSerial();
                        } else {
                            imei = telephonyManager.getDeviceId();
                        }

                    if (imei == null || imei.length() == 0 || imei.substring(0, 2).equals("35")) {
                        Message msg = new Message();
                        Bundle bd = new Bundle();
                        bd.putString("imei", "正在获取");
                        msg.setData(bd);
                        msg.what = 0;
                        handler.sendMessage(msg);
                        try {
                            Thread.sleep(2000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Message msg = new Message();
                        Bundle bd = new Bundle();
                        bd.putString("imei", imei);
                        msg.setData(bd);
                        msg.what = 1;
                        handler.sendMessage(msg);
                        break;
                    }
                }
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String imei = msg.getData().getString("imei");
                    bar_imei.setText(imei);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public void initNetwork() {
        registerPhoneStateListerer();
    }

    public void registerPhoneStateListerer() {
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
            intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
            intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
            context.registerReceiver(networkChangeReceiver, intentFilter);
        }
    }

    public static BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            getNetworkInfo();
        }
    };

    public PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
            try {
                Class<SignalStrength> c = SignalStrength.class;
                Method method = c.getDeclaredMethod("getLevel");
                int level = (Integer) method.invoke(signalStrength);
                Log.i(TAG, "onSignalStrengthsChanged: " + level);
                strength = level * 8;
            } catch (Exception e) {
                e.printStackTrace();
            }

//            strength = signalStrength.getGsmSignalStrength();
            getNetworkInfo();
        }
    };

    public static void getNetworkInfo() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info == null || !info.isAvailable()) {
            gprs_signal.setText("00%");
        } else {

            // signal image
            switch (info.getType()) {
                case ConnectivityManager.TYPE_WIFI:
                    signal_type_image.setImageResource(R.mipmap.signal_wifi);
                    break;
                case ConnectivityManager.TYPE_MOBILE:
                    signal_type_image.setImageResource(R.mipmap.signal_lte);
                    break;
            }

            // signal strength
            int GPRS_SIGNAL = 0;
            switch (info.getType()) {
                case ConnectivityManager.TYPE_WIFI:
                    WifiManager manager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = manager.getConnectionInfo();
                    int rssi = wifiInfo.getRssi();
                    int level = WifiManager.calculateSignalLevel(rssi, 33);
//                    Log.d(TAG, "getNetworkInfo: rssi = " + rssi + " level = " + level);
                    GPRS_SIGNAL = level;
                    break;
                case ConnectivityManager.TYPE_MOBILE:
//                    Log.d(TAG, "getNetworkInfo: strength = " + strength);
                    if (strength > 32) {
                        strength = 32;
                    }
                    GPRS_SIGNAL = strength;
                    break;
            }
            signal = Math.round(GPRS_SIGNAL * 100.0 / 32);
            gprs_signal.setText("" + signal + "%");
            networkFlag = true;
        }
    }

    public void stop() {
    }
}
